import { Controller } from 'egg'

export default class TableController extends Controller {
  // 全查
  async list() {
    const { ctx } = this
    const tableList = await ctx.service.table.list()
    ctx.body = tableList
  }

  // 单查 /table/findOne?id=x
  async findOne() {
    const { ctx } = this
    const id = ctx.query.id
    const result = await ctx.model.Table.findByPk(id)
    ctx.body = result
  }

  // 增
  async create() {
    const { ctx } = this
    const body = ctx.request.body
    // TODO validate
    const result = await ctx.model.Table.create(body)
    ctx.status = 201
    ctx.body = result
  }

  // 改
  async update() {
    const { ctx } = this
    ctx.logger.info('id', ctx.query.id)
    const instance = await ctx.model.Table.findByPk(ctx.query.id)
    if (!instance) {
      ctx.status = 404
      ctx.body = '未查到需要修改的菜单'
    }

    else {
      const { title } = ctx.request.body
      await instance.update({ title })
      ctx.body = instance
    }
  }
}